<template>
  <div v-if="product" class="product-container" style="height: 100vh; overflow: auto;">
      <el-breadcrumb separator="> " class="page-breadcrumb">
      <el-breadcrumb-item @click.native="goToIndex">返回首页</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="product-header">
      <!-- 主图区域（居中显示） -->
      <div class="product-media">
        <div class="image-wrapper">
          <img 
            :src="selectedSku?.skuImage || product.mainImage" 
            alt="商品主图" 
            class="product-main-image" 
            @error="handleImageError"
          />
        </div>
      </div>

      <!-- 信息区域 -->
      <div class="product-meta">
        <h1 class="product-title">{{ product.title }}</h1>
        
        <!-- 价格展示 -->
        <p class="product-price">
          ¥{{ selectedSku?.price || product.skuList?.[0]?.price || '暂无价格' }}
        </p>
        
        <!-- 商品描述 -->
        <div class="product-desc" v-html="product.detailHtml"></div>
        
        <!-- 规格选择区 -->
        <div class="spec-groups">
          <div 
            v-for="(specValues, specKey) in availableSpecs" 
            :key="specKey" 
            class="spec-group"
          >
            <h3 class="spec-title">{{ formatSpecKey(specKey) }}</h3>
            <div class="spec-options">
              <span 
                v-for="value in specValues" 
                :key="value"
                class="spec-option"
                :class="{ selected: selectedSpecs[specKey] === value }"
                @click="selectSpec(specKey, value)"
              >
                {{ value }}
              </span>
            </div>
          </div>
        </div>

        <!-- 库存展示 -->
        <p class="stock-info" v-if="selectedSku">
          库存：{{ selectedSku.stock }} 件
        </p>

        <!-- 数量选择 -->
        <div class="quantity-selector" v-if="selectedSku">
          <el-input-number
            v-model="quantity"
            :min="1"
            :max="selectedSku.stock"
            label="数量"
          ></el-input-number>
        </div>

        <!-- 加入购物车按钮 -->
        <el-button 
          type="primary" 
          class="buy-add-button"
          @click="handleAddToCart"
          :disabled="!selectedSku"
        >
          加入购物车
        </el-button>

        <!-- 立即购买按钮 -->
        <el-button 
          type="primary" 
          class="buy-add-button"
          @click="handleBuyNow"
          :disabled="!selectedSku"
        >
          立即购买
        </el-button>
      </div>
    </div>

    <!-- 用户评价 -->
    <el-divider content-position="left">用户评价</el-divider>
    <div class="evaluation-section">
      <el-empty description="暂无评价" v-if="!evaluations.length" />

      <el-card
        v-for="item in evaluations"
        :key="item.id"
        class="eval-card"
        shadow="hover"
      >
        <template #header>
          <div class="eval-header">
            <span class="eval-username">{{ item.username || '匿名用户' }}</span>
            <el-rate :model-value="item.score" disabled show-score />
            <span class="eval-time">{{ formatDate(item.createTime) }}</span>
          </div>
        </template>
        <p class="eval-content">{{ item.content }}</p>

        <div v-if="item.imageList && item.imageList.length" class="eval-images">
          <img
            v-for="(img, idx) in item.imageList"
            :key="idx"
            :src="formatImgUrl(img)"
            class="eval-img"
            @error="handleImageError"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElInputNumber } from 'element-plus';
import service from '@/utils/request';
import { getProductWithSku, getProductEvaluationsService } from '@/api/product';
import { addCartService } from '@/api/user';

const route = useRoute();
const router = useRouter();
const product = ref(null);
const selectedSku = ref(null);
const quantity = ref(1);
const selectedSpecs = ref({});
const evaluations = ref([]);
const evalPage = ref(1);
const evalPageSize = 10;
const evalTotal = ref(0);
const loadingEval = ref(false);

const goToIndex = () => router.push('/index')

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src);
  // 可以在这里设置备用图片
  event.target.src = 'https://picsum.photos/800/800?blur=3&text=Error+Loading+Image';
};

// 补全图片地址
const backendHost = 'http://localhost:8080';
const formatImgUrl = (url) => {
  if (!url) return '';
  if (url.startsWith('http')) return url;
  return backendHost + url;
};

const availableSpecs = computed(() => {
  if (!product.value?.skuList?.length) return {};
  
  const specsMap = {};
  
  // 遍历所有SKU，收集规格
  product.value.skuList.forEach(sku => {
    const specs = parseSpecs(sku.specsJson);
    Object.entries(specs).forEach(([key, value]) => {
      if (!specsMap[key]) {
        specsMap[key] = new Set(); // 用Set去重
      }
      specsMap[key].add(value);
    });
  });
  
  // 转换为数组格式
  return Object.fromEntries(
    Object.entries(specsMap).map(([key, values]) => [
      key, Array.from(values)
    ])
  );
});

// 保存 productId 全局
const productIdGlobal = ref(null);

onMounted(async () => {
  const productId = route.params.id;
  productIdGlobal.value = productId;
  console.log(productId);
  try {
    const res = await getProductWithSku(productId);
    if (res.data.code == 200 || res.data.code == "200") {
      product.value = null;
      await nextTick();
      product.value = res.data.data; // 真实数据
      // 兼容后端字段名 skulist
      if (!product.value.skuList && product.value.skulist) {
        product.value.skuList = product.value.skulist;
      }
      // 初始化选中第一个SKU
      if (product.value?.skuList?.length) {
        selectedSku.value = product.value.skuList[0];
        const firstSpecs = parseSpecs(selectedSku.value.specsJson);
        selectedSpecs.value = { ...firstSpecs };
      }
      // 首次加载评价
      await fetchEvaluations();
      // 监听滚动加载更多
      window.addEventListener('scroll', handleScroll, { passive: true });
    } else {
      ElMessage.error(res.data.message || '商品不存在');
    }
  } catch (error) {
    ElMessage.error('商品数据加载失败');
    console.error('加载失败原因：', error);
  }
});

import { onUnmounted } from 'vue';
import {addOrderApi} from '@/api/pay'
import { useUserInfoStore } from '@/stores/userInfo'


const userStore = useUserInfoStore(); 
const userId = computed(() => userStore.userInfo?.id);
const fetchEvaluations = async () => {
  if (loadingEval.value) return;
  loadingEval.value = true;
  const res = await getProductEvaluationsService(productIdGlobal.value, evalPage.value, evalPageSize);
  if (res.data.code == 200 || res.data.code == '200') {
    const { records, total } = res.data.data;
    // 解析图片 JSON
    records.forEach(item => {
      if (item.images) {
        try {
          item.imageList = JSON.parse(item.images);
        } catch (e) {
          item.imageList = item.images.split(',');
        }
      } else {
        item.imageList = [];
      }
    });
    evaluations.value.push(...records);
    evalTotal.value = total;
  }
  loadingEval.value = false;
};

const handleScroll = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  const windowHeight = window.innerHeight;
  const docHeight = document.documentElement.scrollHeight;
  if (scrollTop + windowHeight + 100 >= docHeight) {
    if (evaluations.value.length < evalTotal.value) {
      evalPage.value += 1;
      fetchEvaluations();
    }
  }
};

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});

// 解析规格JSON
const parseSpecs = (specsJson) => {
  try {
    let cleaned = specsJson.replace(/\\"/g, '"');
    cleaned = cleaned.replace(/^"|"$/g, ''); 
    return JSON.parse(cleaned);
  } catch (error) {
    console.error('规格解析失败:', error);
    return {};
  }
};

// 格式化规格键名
const formatSpecKey = (key) => {
  const specMap = {
    'color': '颜色',
    'processor': '处理器',
    'graphics_card': '显卡',
    'memory': '内存',
    'storage': '存储',
    'size': '尺寸'
  };
  return specMap[key] || key;
};

// 选择规格（改进逻辑）
const selectSpec = (specKey, value) => {
  // 更新选中的规格
  selectedSpecs.value = {
    ...selectedSpecs.value,
    [specKey]: value
  };
  
  // 查找匹配当前规格组合的SKU
  const matchedSku = product.value.skuList.find(sku => {
    const skuSpecs = parseSpecs(sku.specsJson);
    // 检查所有已选中的规格是否匹配
    return Object.entries(selectedSpecs.value).every(
      ([key, val]) => skuSpecs[key] === val
    );
  });
  
  // 如果找到匹配的SKU，更新selectedSku
  // 如果没有找到，保留当前selectedSku，不设为null
  if (matchedSku) {
    selectedSku.value = matchedSku;
  } else {
    console.warn('没有找到完全匹配的SKU，使用第一个SKU保持图片显示');
    // 如果没有完全匹配的SKU，使用第一个SKU确保图片继续显示
    if (product.value.skuList?.length && !selectedSku.value) {
      selectedSku.value = product.value.skuList[0];
    }
  }
};

// 加入购物车逻辑
const handleAddToCart = async () => {
  // 1. 校验规格和库存
  if (!selectedSku.value) {
    ElMessage.warning('请选择完整规格~');
    return;
  }
  if (quantity.value > selectedSku.value.stock) {
    ElMessage.warning('库存不足~');
    return;
  }
  // console.log(selectedSku);
  // console.log(quantity);
  // console.log(selectedSpecs);
  // 2. 调用接口
  try {
    const res = await addCartService({
      productId: selectedSku.value.id, // 对应后端CartItemDTO的productId
      quantity: quantity.value
    });
    
    ElMessage.success('已加入购物车');
    console.log('添加结果:', res); // 可查看后端返回数据
  } catch (error) {
    ElMessage.error('添加失败: ' + error.message);
  }
};

const handleBuyNow = async () => {
  // 1. 强制校验用户和商品数据
  console.log(userStore.id)
  console.log(selectedSku.value)
  if (!userId.value || !selectedSku.value) {
    ElMessage.error('请先登录并选择商品规格');
    return;
  }

  try {
    // 2. 调用订单接口（打印请求参数）
    console.log('订单请求参数:', {
      userId: userStore.id,
      skuId: selectedSku.value.id,
      quantity: quantity.value
    });

    const orderRes = await addOrderApi({
      userId: userStore.id,
      skuId: selectedSku.value.id,
      quantity: quantity.value
    });

    console.log(orderRes)
     
    

    // 4. 跳转支付页（打印调试信息）
    if (orderRes.data.code !== '200') {
      throw new Error(orderRes.data?.message || '订单创建失败');
    }
    router.push({ path: '/pay/choose', query: { orderSn: orderRes.data.data.orderSn } })

  } catch (error) {
    console.error('订单创建失败详情:', {
      error: error.message,
      response: error.response?.data
    });
    ElMessage.error(`订单创建失败: ${error.response?.data?.message || error.message}`);
  }
};



// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};
</script>

<style scoped>
/* 容器样式 */
.product-container {
  max-width: 1200px;
  margin: 40px auto;
  padding: 30px;
  font-family: "Segoe UI", sans-serif;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

/* 头部布局 - 左右分栏 */
.product-header {
  display: grid;
  grid-template-columns: 1fr 1.2fr; /* 主图区域略窄，信息区略宽 */
  gap: 50px;
  align-items: start;
}

/* 主图区域（居中核心优化） */
.product-media {
  display: flex;
  justify-content: center; /* 水平居中 */
  padding: 20px;
  background: #fafafa;
  border-radius: 12px;
}

.image-wrapper {
  max-width: 500px; /* 限制最大宽度 */
  width: 100%;
}

.product-main-image {
  width: 100%;
  height: auto;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  transition: transform 0.3s ease;
}

.product-main-image:hover {
  transform: scale(1.02);
}

/* 信息区域样式 */
.product-meta {
  padding: 10px 0;
}

.product-title {
  font-size: 28px;
  font-weight: 700;
  color: #111;
  margin-bottom: 20px;
  line-height: 1.3;
}

.product-price {
  font-size: 28px;
  font-weight: bold;
  color: #e60012;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

/* 规格选择区 */
.spec-groups {
  margin: 0 0 30px;
}

.spec-group {
  margin-bottom: 20px;
}

.spec-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.spec-title::after {
  content: '';
  flex: 1;
  height: 1px;
  background: #f0f0f0;
  margin-left: 10px;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.spec-option {
  padding: 10px 20px;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}

.spec-option:hover {
  border-color: #409eff;
}

.spec-option.selected {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
  font-weight: 500;
}

/* 库存和数量 */
.stock-info {
  color: #666;
  margin: 15px 0;
  font-size: 14px;
}

.quantity-selector {
  margin: 20px 0;
  width: 150px;
}

/* 按钮样式 */
.buy-add-button {
  margin: 25px 0 30px;
  padding: 12px 40px;
  font-size: 16px;
  border-radius: 6px;
}

/* 商品描述 */
.product-desc {
  font-size: 15px;
  color: #555;
  line-height: 1.8;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式调整 - 小屏幕下堆叠显示 */
@media (max-width: 768px) {
  .product-header {
    grid-template-columns: 1fr;
    gap: 30px;
  }
  
  .product-media {
    padding: 15px;
  }
}

.evaluation-section {
  margin-top: 40px;
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}
.eval-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 16px;
}
.evaluation-item {
  margin-bottom: 16px;
}
.eval-score {
  color: #e6a23c;
  margin-right: 8px;
}
.eval-time {
  color: #999;
  font-size: 12px;
  margin-left: 10px;
}

.eval-card {
  margin-bottom: 15px;
}

.eval-header {
  display: flex;
  gap: 8px;
  justify-content: space-between;
  align-items: center;
}

.eval-username {
  font-weight: 600;
  margin-right: auto;
}

.eval-content {
  font-size: 15px;
  color: #333;
  line-height: 1.6;
  margin-top: 10px;
}

.eval-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.eval-img {
  max-width: 100px;
  height: auto;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.buy-add-button + .buy-add-button {
  margin-left: 16px;
}

.page-breadcrumb {
  margin-bottom: 10px;
  font-size: 14px;
}
.page-breadcrumb ::v-deep(.el-breadcrumb__item a) {
  color: #409eff;
  cursor: pointer;
}
</style>